package com.study.account.controller;

import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.Random;

/**
 * @author
 */
@Slf4j
@RestController
public class AccountController {

	private static final String SUCCESS = "SUCCESS";
	private static final String FAIL = "FAIL";

	private final JdbcTemplate jdbcTemplate;
	private Random random;

	public AccountController(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
		this.random = new Random();
	}

	@RequestMapping(value = "/account", method = RequestMethod.POST, produces = "application/json")
	public String account(String userId, int money) {
		log.info("Account Service ... xid: " + RootContext.getXID());
		if (random.nextBoolean()) {
			log.info("random exception userId={},money={}",userId,money);
			throw new RuntimeException("this is a mock Exception");
		}

		String sql = "update account_tbl set money = money - ? where user_id = ?";
		int result = jdbcTemplate.update(sql, new Object[] { money, userId });
		log.info("Account Service End ... result={},sql={}",result,sql);
		return (result == 1) ?SUCCESS: FAIL;
	}

}